﻿using CsvHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using Util.Model;

namespace Util
{
    public class CSVUtil
    {

        /// <summary>
        /// 写入到CSV文件
        /// </summary>
        /// <param name="dataList">要写入的CSVData对象</param>
        /// <param name="storageDirectory">要存储到的文件夹</param>
        /// <param name="fileName">存储的文件名</param>
        public async Task WriteToCsvAsync(List<CSVData2> dataList, List<Border> borderList, string storageDirectoryAndName)
        {
            string fileName = Path.GetFileName(storageDirectoryAndName);
            if (!fileName.EndsWith(".csv"))
            {
                fileName = fileName + ".csv";
            }
            string filePath = storageDirectoryAndName;

            string directoryPath = Path.GetDirectoryName(filePath);
            Directory.CreateDirectory(directoryPath);
            // 清空原有文件内容（如果文件存在）
            try
            {
                // 清空原有文件内容（如果文件存在）
                if (File.Exists(filePath))
                {
                    File.WriteAllText(filePath, string.Empty);  // 清空文件内容
                }
            }
            catch
            {

            }

            bool includeHeader = !File.Exists(filePath);

            // 使用 UTF-8 编码并添加 BOM
            using (StreamWriter writer = new StreamWriter(filePath, append: true, Encoding.UTF8))
            using (CsvWriter csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                if (includeHeader)
                {
                    csvWriter.WriteHeader<CSVData2>();
                    csvWriter.NextRecord();
                }

                foreach (var data in dataList)
                {
                    csvWriter.WriteRecord(data);
                    csvWriter.NextRecord();
                }
            }
            //写入数据库的功能要再实现的时候写，因为工具项目不能引用数据库项目，否则会形成循环依赖
        }

        public async Task WriteToCsvAsync(List<CSVData> dataList, List<Border> borderList, string storageDirectoryAndName)
        {
            string fileName = Path.GetFileName(storageDirectoryAndName);
            if (!fileName.EndsWith(".csv"))
            {
                fileName = fileName + ".csv";
            }
            string filePath = storageDirectoryAndName;

            string directoryPath = Path.GetDirectoryName(filePath);
            Directory.CreateDirectory(directoryPath);

            try
            {
                // 清空原有文件内容（如果文件存在）
                if (File.Exists(filePath))
                {
                    File.WriteAllText(filePath, string.Empty);  // 清空文件内容
                }
            }
            catch
            {
               
            }
            


            bool includeHeader = !File.Exists(filePath);

            // 使用 UTF-8 编码并添加 BOM
            using (StreamWriter writer = new StreamWriter(filePath, append: true, Encoding.UTF8))
            using (CsvWriter csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                if (includeHeader)
                {
                    csvWriter.WriteHeader<CSVData>();
                    csvWriter.NextRecord();
                }

                foreach (var data in dataList)
                {
                    csvWriter.WriteRecord(data);
                    csvWriter.NextRecord();
                }
            }
            //写入数据库的功能要再实现的时候写，因为工具项目不能引用数据库项目，否则会形成循环依赖
        }


        public async Task WriteToCsvAsync(List<CSVData3> dataList, List<Border> borderList, string storageDirectoryAndName)
        {
            string fileName = Path.GetFileName(storageDirectoryAndName);
            if (!fileName.EndsWith(".csv"))
            {
                fileName = fileName + ".csv";
            }
            string filePath = storageDirectoryAndName;

            string directoryPath = Path.GetDirectoryName(filePath);
            Directory.CreateDirectory(directoryPath);
            // 清空原有文件内容（如果文件存在）
            try
            {
                // 清空原有文件内容（如果文件存在）
                if (File.Exists(filePath))
                {
                    File.WriteAllText(filePath, string.Empty);  // 清空文件内容
                }
            }
            catch
            {

            }

            bool includeHeader = !File.Exists(filePath);

            // 使用 UTF-8 编码并添加 BOM
            using (StreamWriter writer = new StreamWriter(filePath, append: true, Encoding.UTF8))
            using (CsvWriter csvWriter = new CsvWriter(writer, CultureInfo.InvariantCulture))
            {
                if (includeHeader)
                {
                    csvWriter.WriteHeader<CSVData3>();
                    csvWriter.NextRecord();
                }

                foreach (var data in dataList)
                {
                    csvWriter.WriteRecord(data);
                    csvWriter.NextRecord();
                }
            }
            //写入数据库的功能要再实现的时候写，因为工具项目不能引用数据库项目，否则会形成循环依赖
        }

        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="storageDirectory">要读取的文件夹</param>
        /// <param name="fileName">要读取文件名</param>
        /// <param name="CSVDataList">CSVData对象列表</param>
        /// <param name="BorderList">Border对象列表</param>
        public void ReadFromCsv(string storageDirectory, string fileName, out List<CSVData> CSVDataList, out List<Border> BorderList)
        {
            string relativePath = Path.Combine("CSV", storageDirectory, fileName);
            string filePath = Path.Combine(Directory.GetCurrentDirectory(), relativePath);

            //判定框数量
            string strNum = fileName.Split('-')[1].Split(".")[0];
            int num = Convert.ToInt32(strNum);

            List<CSVData> data = new();
            List<Border> border = new();

            using (StreamReader reader = new(filePath, Encoding.UTF8))

            using (CsvReader borderCsv = new(reader, CultureInfo.InvariantCulture))
            {

                while (borderCsv.Read())
                {
                    int rowIndex = borderCsv.Parser.Row;
                    if (rowIndex <= num + 1 && num != 0)
                    {
                        Border borderObj = borderCsv.GetRecord<Border>();
                        border.Add(borderObj);
                    }
                }
            }
            //这里写两个是因为 CsvReader 的表头是固定的，这里存了两个表相当于
            using (StreamReader reader = new(filePath))
            using (CsvReader csv = new(reader, CultureInfo.InvariantCulture))
            {

                while (csv.Read())
                {
                    int rowIndex = csv.Parser.Row;
                    if (rowIndex >= 2 + num)
                    {
                        CSVData obj = csv.GetRecord<CSVData>();
                        data.Add(obj);
                    }
                }
            }

            CSVDataList = data;
            BorderList = border;
        }

        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="storageDirectory">要读取的文件夹</param>
        /// <param name="fileName">要读取文件名</param>
        /// <param name="CSVDataList">CSVData对象列表</param>
        /// <param name="BorderList">Border对象列表</param>
        public void ReadFromCsv(string filePath, out List<CSVData> CSVDataList, out List<Border> BorderList)
        {
            string fileName = Path.GetFileName(filePath);
            //判定框数量
            string strNum = Regex.Match(fileName.Replace(".csv",""), @"\d+$").Value;
            int num = Convert.ToInt32(strNum);

            List<CSVData> data = new();
            List<Border> border = new();


            using (StreamReader reader = new(filePath, Encoding.UTF8))

            using (CsvReader borderCsv = new(reader, CultureInfo.InvariantCulture))
            {

                while (borderCsv.Read())
                {
                    int rowIndex = borderCsv.Parser.Row;
                    if (rowIndex <= num + 1 && num != 0)
                    {
                        Border borderObj = borderCsv.GetRecord<Border>();
                        border.Add(borderObj);
                    }
                }
            }
            //这里写两个是因为 CsvReader 的表头是固定的，这里存了两个表相当于
            using (StreamReader reader = new(filePath))
            using (CsvReader csv = new(reader, CultureInfo.InvariantCulture))
            {

                while (csv.Read())
                {
                    int rowIndex = csv.Parser.Row;
                    if (rowIndex >= 2 + num)
                    {
                        try
                        {
                            CSVData obj = csv.GetRecord<CSVData>();
                            data.Add(obj);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("文件的标头格式有误，请对照生成的文件进行修改再查看");
                            break;
                        }

                    }
                }
            }

            CSVDataList = data;
            BorderList = border;
        }
    }
}
